package net.gazhi.delonix.core.web;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.gazhi.delonix.core.entity.LoginUser;
import net.gazhi.delonix.core.thread.ThreadContext;

import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 线程上下文重置过滤器<br>
 * <br>
 * 先清空线程上下文，然后把 application context 和 loginUser 缓存到当前线程</br>
 * 请求处理结束后，再次清空上下文，以释放内存资源和防止不同请求的数据污染
 * 
 * @author Jeffrey Lin
 *
 */
public class ResetThreadContextFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		ThreadContext.clear();
		ThreadContext.setAppContext(WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()));
		ThreadContext.setLoginUser(LoginUser.getLoginUser(request.getSession()));
		filterChain.doFilter(request, response);
		ThreadContext.clear();
	}

}